package com.passion.context;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import com.passion.common.util.StringUtils;
import com.passion.domain.entity.SysUser;
import com.passion.service.SysUserService;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;

/**
 * 类描述：用户上下文
 *
 * @author ZhuYin
 * @since 2024年12月26日
 */
@Slf4j
@Data
@Component
@NoArgsConstructor
public class UserContext implements Serializable {

    private static final long serialVersionUID = 1L;

    @Resource
    private SysUserService sysUserService;

    private static SysUser sysUser;
    public void setSysUser(SysUser sysUser) {
        UserContext.sysUser = sysUser;
    }

    public SysUser getSysUser() {
        if (sysUser != null) {
            return sysUser;
        } else {
            String userId;
            try {
                userId = StpUtil.getLoginIdAsString();
            } catch (Exception e) {
                // 非web上下文环境可能无法获取到用户对象
                if (e instanceof SaTokenException && "非Web上下文无法获取Request".equals(e.getMessage())) {

                } else {
                    log.warn("获取用户信息失败:{}", e.getMessage());
                }
                return null;
            }
            if (StringUtils.isNotBlank(userId)) {
                sysUser = (SysUser) StpUtil.getSession().get("loginUser");
            }
            return sysUser;
        }
    }

    public static String deptId;
    public void setDeptId(String deptId) {
        UserContext.deptId = deptId;
    }

    public static Set<String> roleCodes;
    public void setRoleCodes(Set<String> roleCodes) {
        UserContext.roleCodes = roleCodes;
    }

    public static Set<String> permissions;
    public void setPermissions(Set<String> permissions) {
        UserContext.permissions = permissions;
    }

    public static String getUserId() {
        if (sysUser != null) {
            return sysUser.getId();
        }
        return "";
    }

}
